package com.rfs.juc;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author renfushuai
 * @date 2022/12/7
 */
public class AtomicIntegerDemo {
    private AtomicInteger atomicI=new AtomicInteger(0);
    private int i=0;
    private void safeCount(){
        for (;;){
            int i=atomicI.get();
            boolean suc=atomicI.compareAndSet(i,++i);
            if (suc) {
                break;
            }
        }
    }
    private void count(){
        i++;
    }

    public static void main(String[] args) {
        ArrayList<Thread> ts = new ArrayList<>();
        AtomicIntegerDemo atomicIntegerDemo = new AtomicIntegerDemo();
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    atomicIntegerDemo.safeCount();
                    atomicIntegerDemo.count();
                }
            });
            ts.add(t);
        }
        for (Thread t : ts) {
            t.start();
        }
        for (Thread t : ts) {
            try {
                t.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(atomicIntegerDemo.i);
        System.out.println(atomicIntegerDemo.atomicI.get());
    }
}
